package com.zkyc.framework.website.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.mapper.*;
import com.zkyc.framework.common.pojo.*;
import com.zkyc.framework.common.pool.GlobalThreadPoolExecutor;
import com.zkyc.framework.common.utils.ExcelUtil;
import com.zkyc.framework.common.utils.PageUtil;
import com.zkyc.framework.common.utils.WebsiteUtil;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.common.vo.website.*;
import com.zkyc.framework.website.client.AlgorithmClient;
import com.zkyc.framework.website.client.FileClient;
import com.zkyc.framework.website.client.RoleClient;
import com.zkyc.framework.website.client.UserClient;
import com.zkyc.framework.website.config.JedisPoolFactory;
import com.zkyc.framework.website.config.MathcingConfig;
import com.zkyc.framework.website.mapper.*;
import com.zkyc.framework.website.service.ContentService;
import com.zkyc.framework.website.strategy.StrategyEnum;
import com.zkyc.framework.website.strategy.StrategyHandler;
import com.zkyc.framework.website.util.TokenUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.zkyc.framework.common.constant.Constant.*;


/**
 * @author bing.bai
 * @create 2022/5/25
 */
@Service
@Slf4j
public class ContentServiceImpl implements ContentService {

    private static final String LOCK_KEY = REDIS_PREFIX + "GetMaxContentIdLock";
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";

    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private MoudleMapper moudleMapper;

    @Autowired
    private ColumnMapper columnMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private QuoteMapper quoteMapper;

    @Autowired
    private CenterMapper centerMapper;

    @Autowired
    MediaMapper mediaMapper;

    @Autowired
    private ContentRefMediatagMapper contentRefMediatagMapper;

    @Autowired
    private AlgorithmClient algorithmClient;

    @Autowired
    private ContentRefMediatagMapper contntRefMediatagMapper;

    @Autowired
    private MediaTagMapper mediaTagMapper;

    @Autowired
    private MediaTagGroupMapper mediaTagGroupMapper;

    @Autowired
    private SystemDictionaryMapper systemDictionaryMapper;

    @Autowired
    private FileRefContentMapper fileRefContentMapper;

    @Autowired
    private FileClient fileClient;

    @Autowired
    SystemFileRefSubjectMapper systemFileRefSubjectMapper;

    @Autowired
    SystemFileRefTagMapper systemFileRefTagMapper;

    @Autowired
    RoleClient roleClient;

    @Autowired
    private ApproveMapper approveMapper;

    @Autowired
    private ApproveServiceImpl approveService;

    public static HashSet<String> completeMatchingSet = new HashSet<String>() {{
    }};


    @Autowired
    private ClickRateMapper clickRateMapper;

    @Override
    @Transactional
    public ResultVO addContent(WebContentVo webContent) {
        String websiteId = WebsiteUtil.getWebsiteId();
        if (StringUtils.isNotBlank(websiteId)) {
            webContent.setWebsiteId(Integer.parseInt(websiteId));
        }
        String contentTitle = webContent.getContentTitle();
        Integer centerId = webContent.getCenterId();
        Integer columnId = webContent.getColumnId();
        if (StringUtils.isBlank(contentTitle)) {
            return ResultVO.fail("标题不能为空");
        } else {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("content_title", contentTitle);
            queryWrapper.eq("center_id", centerId);
            queryWrapper.eq("column_id", columnId);
            List contentList = contentMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(contentList)) {
                return ResultVO.fail("该标题已存在");
            }
        }

        Date date = new Date();
        webContent.setGmtCreated(date);
        webContent.setGmtUpdated(date);
        if (webContent.getStatus() == 1) {
            webContent.setPublishTime(date);
        }
        webContent.setIsDeleted(0);
        Column column = columnMapper.selectById(columnId);
        Moudle moudle = moudleMapper.selectById(column.getMoudleId());
        webContent.setPath(moudle.getMoudleName() + "/" + column.getColumnName());
        String currentUserId = TokenUserUtil.getCurrentUserId();
        ResultVO<?> userById = userClient.getUserById(currentUserId);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
        User user = JSONObject.parseObject(jsonObject.getString("data"), User.class);
        webContent.setCreatedBy(user.getUsername());
        contentMapper.insert(webContent);
        insertRef(webContent);
        //标签绑定关系
        /*if (webContent.getTagGroup() != null) {
            for (TagGroupVo tagGroupVo : webContent.getTagGroup()) {
                tagGroupVo.getTagVoList().forEach(a -> {
                    ContentRefMediatag contentRefMediatag = new ContentRefMediatag();
                    contentRefMediatag.setContentId(webContent.getId());
                    contentRefMediatag.setMediaTagId(a.getId());
                    contentRefMediatag.setGmtCreated(date);
                    contentRefMediatag.setGmtUpdated(date);
                    contentRefMediatagMapper.insert(contentRefMediatag);
                });
            }
        }*/
        if (webContent.getMediaId() != null) {
            FileRefContent fileRefContent = new FileRefContent();
            fileRefContent.setContentId(webContent.getId());
            fileRefContent.setFileId(webContent.getMediaId());
            fileRefContentMapper.insert(fileRefContent);
        }
        return ResultVO.data(webContent.getId());
    }

    @Override
    public ResultVO submit(WebContentVo webContent) {
        if (webContent.getId() != null) {
            Approve approve = approveMapper.selectOne(new LambdaQueryWrapper<Approve>().eq(Approve::getPid, webContent.getId()).eq(Approve::getType, 1));
            if (approve != null) {
                //已驳回的要进行重置
                if (approve.getStatus() == 2) {
                    approveMapper.deleteById(approve);
                } else {
                    return ResultVO.fail(ResultCode.APPROVE_DUPLICATION);
                }
            }
        }
        if (webContent.getId() == null) {
            addContent(webContent);
        } else {
            update(webContent);
        }
        Approve approve = new Approve();
        approve.setCenterId(webContent.getCenterId());
        approve.setLevel(1);
        approve.setType(1);
        approve.setCreatedBy(webContent.getCreatedBy());
        approve.setStatus(0);
        approve.setPid(webContent.getId());
        approveMapper.insert(approve);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO offLine(String id) {
        if (id != null) {
            List<Approve> approves = approveMapper.selectList(new LambdaQueryWrapper<Approve>().eq(Approve::getPid, id)
                    .and(x -> x.eq(Approve::getType, 1).or().eq(Approve::getType, 3)));
            for (Approve approve : approves) {
                //审批全部下线
                approveMapper.deleteById(approve.getId());
            }
            //删除推荐表
            quoteMapper.delete(new LambdaQueryWrapper<WebQuoteContent>().eq(WebQuoteContent::getContentId, id));
            WebContent content = contentMapper.selectById(id);
            content.setStatus(3);
            contentMapper.updateById(content);
            return ResultVO.success(ResultCode.SUCCESS);
        }
        return ResultVO.fail(ResultCode.FAILURE);
    }

    private void insertRef(WebContentVo webContent) {
        insertFileRefContent(webContent);
        ContentRefMediatag contentRefMediatag = new ContentRefMediatag();
        if (webContent.getTagId() != null && webContent.getTagId().size() > 0) {
            List<List<Integer>> tagIdList = webContent.getTagId();
            for (List<Integer> integers : tagIdList) {
                contentRefMediatag.setContentId(webContent.getId());
                contentRefMediatag.setMediaTagId(integers.get(integers.size() - 1));
                contentRefMediatag.setGmtCreated(new Date());
                contentRefMediatag.setGmtUpdated(new Date());
                contentRefMediatagMapper.insert(contentRefMediatag);
            }
        }
    }


    @Override
    @Transactional
    public ResultVO update(WebContentVo webContent) {
        //校验修改后的名称不存在
        WebContent dbContent = contentMapper.selectById(webContent.getId());
        if (!dbContent.getContentTitle().equals(webContent.getContentTitle())) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("content_title", webContent.getContentTitle());
            WebContent webContentByTitle = contentMapper.selectOne(queryWrapper);
            if (webContentByTitle != null) {
                return ResultVO.fail("稿件标题已存在");
            }
        }
        Date date = new Date();
        webContent.setGmtUpdated(date);
/*        if (webContent.getStatus() != null && webContent.getStatus() == 1) {
            webContent.setPublishTime(date);
        }*/
        if (webContent.getStatus() == 1 && webContent.getPublishTime() == null) {
            webContent.setPublishTime(date);
        }
        contentMapper.updateById(webContent);
        HashMap map = new HashMap();
        map.put("content_id", webContent.getId());
        contentRefMediatagMapper.deleteByMap(map);
        insertRef(webContent);
/*        if (webContent.getTagGroup() != null) {
            for (TagGroupVo tagGroupVo : webContent.getTagGroup()) {
                tagGroupVo.getTagVoList().forEach(a -> {
                    ContentRefMediatag contentRefMediatag = new ContentRefMediatag();
                    contentRefMediatag.setContentId(webContent.getId());
                    contentRefMediatag.setMediaTagId(a.getId());
                    contentRefMediatag.setGmtCreated(date);
                    contentRefMediatag.setGmtUpdated(date);
                    contentRefMediatagMapper.insert(contentRefMediatag);
                });
            }
        }*/
        JedisPoolFactory.delete(REDIS_PREFIX + CONTENTKEY + webContent.getId());
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO list(Integer id, String createdBy, String beginDate, String endDate, String title, Integer status, Integer columnId, Integer tag, Integer centerId, Integer current, Integer size) {
        if (columnId == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        return ResultVO.data(getContent(id, createdBy, beginDate, endDate, title, status, columnId, tag, centerId, current, size));
    }

    @Override
    public ResultVO listDashBoard(String beginDate, String endDate, String title, Integer status, Integer columnId, Integer tag, Integer centerId, Integer current, Integer size) {
        if (columnId != null) {
            Column column = columnMapper.selectById(columnId);
            if (column != null && column.getColumnCount() != null) {
                size = column.getColumnCount();
            }
        }
        return ResultVO.data(getContent(null, null, beginDate, endDate, title, status, columnId, tag, centerId, current, size));
    }

    private JSONObject getContent(Integer id, String createdBy, String beginDate, String endDate, String title, Integer status, Integer columnId, Integer tag, Integer centerId, Integer current, Integer size) {
        if (current == null || current == 0) {
            current = 1;
        }
        if (size == null || size == 0) {
            size = 10;
        }
        Integer currentPage = current;
        current = current - 1;
        current = current * 10;
        IPage page = new Page();
        page.setCurrent(currentPage);
        page.setSize(size);
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("column_id", columnId);
//        queryWrapper.orderByDesc("gmt_updated");
//        if (StringUtils.isNotBlank(beginDate)) {
//            queryWrapper.ge("publish_time", beginDate);
//        }
//        if (StringUtils.isNotBlank(endDate)) {
//            queryWrapper.le("publish_time", endDate);
//        }
//        if (StringUtils.isNotBlank(title)) {
//            queryWrapper.like("content_title", title);
//        }
//        if (status != null) {
//            queryWrapper.eq("status", status);
//        }
//        if (centerId != null) {
//            queryWrapper.eq("center_id", centerId);
//        }

        //获取除了标签的分页
        //IPage result = contentMapper.selectPage(page, queryWrapper);
        String userId = TokenUserUtil.getCurrentUserId();
        String websiteId = WebsiteUtil.getWebsiteId();
        String userName = null;
        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(websiteId) && columnId != null) {
            //数据权限
/*            String dataRight = roleClient.getDataRight(websiteId, userId);
            if (StringPool.ZERO.equals(dataRight)) {
                ResultVO<?> userById = userClient.getUserById(userId);
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
                User user = JSONObject.parseObject(jsonObject.getString("data"), User.class);
                userName = user.getUsername();
            }*/
            ResultVO<?> userById = userClient.getUserById(userId);
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
            User user = JSONObject.parseObject(jsonObject.getString("data"), User.class);
            Moudle moudle = moudleMapper.selectById(columnMapper.selectById(columnId).getMoudleId());
            if (user.getCenterId() != null && (moudle.getMoudleName().endsWith("研究院") || moudle.getMoudleName().endsWith("研究中心"))) {
                centerId = user.getCenterId();
            }
        }

        List<WebContentVo> records = contentMapper.contentList(id, createdBy, beginDate, endDate, title, status, columnId, current, size, centerId, tag, userName);
        Integer count = contentMapper.contentCount(id, createdBy, beginDate, endDate, title, status, columnId, centerId, tag, userName);
        Integer pages = (count + size - 1) / size;

        //List<WebContent> records = result.getRecords();
        List<Center> centers = centerMapper.selectList(null);
        HashMap<Integer, String> centerMap = new HashMap<>();
        for (Center center : centers) {
            centerMap.put(center.getId(), center.getCenterName());
        }
        //给每一个转成json
        records.forEach(a -> {
            a.setRejectReason(approveService.setRejectReason(a.getId(), 1));
            Integer click = clickRateMapper.getClick(a.getId());
            if (click == null) {
                click = NumberConstant.NUMBER_0;
            }
            a.setClickRate(click);
            if (StringUtils.isNotBlank(a.getPicUrl())) {
                JSONArray jsonArray = JSONArray.parseArray(a.getPicUrl());
                a.setPicUrlJson(jsonArray);
                if (a.getCenterId() != null) {
                    a.setCenterName(centerMap.get(a.getCenterId()));
                }
            } else {
                a.setPicUrlJson(new JSONArray());
            }
            List tagLists = new LinkedList();
            List<Integer> tagIdList = contentRefMediatagMapper.queryTagIdList(a.getId());
            for (Integer tagRefId : tagIdList) {
                List list = new LinkedList();
                JSONObject jsonObject = mediaMapper.queryTagByTagId(tagRefId);
                if (jsonObject != null) {
                    if (jsonObject.get("tag_group_id") == null) {
                        continue;
                    }
                    list.add(jsonObject.get("tag_group_id"));
                    list.add(jsonObject.get("id"));
                    tagLists.add(list);
                }
            }
            a.setTagId(tagLists);

        });
        //去除关联表中没有的tag
//        if (tag != null) {
//            for (int i = 0; i < records.size(); i++) {
//                JSONObject jsonObject = contentMapper.checkTag(records.get(i).getId(), tag);
//                if (jsonObject == null) {
//                    records.remove(records.get(i));
//                    --i;
//                }
//            }
//        }
        page.setRecords(records);
        page.setTotal(count);
        page.setPages(pages);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(page, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue));
        jsonObject.put("columnName", columnMapper.selectById(columnId) == null ? "" : columnMapper.selectById(columnId).getColumnName());
        jsonObject.put("enName", columnMapper.selectById(columnId) == null ? "" : columnMapper.selectById(columnId).getEnName());
        return jsonObject;
    }

    @Override
    public ResultVO delete(DeleteContentVo deleteContentVo) {
        JedisPoolFactory.delete(REDIS_PREFIX + CONTENTKEY + deleteContentVo.getContentId());
        contentMapper.deleteById(deleteContentVo.getContentId());
        HashMap map = new HashMap();
        map.put("content_id", deleteContentVo.getContentId());
        contentRefMediatagMapper.deleteByMap(map);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO globalList(ColumnDataPageVo columnDataPageVo) {
        int key;
        if ("1".equals(WebsiteUtil.getWebsiteId())) {
            key = StrategyEnum.Aqua.getKey();
        } else {
            key = StrategyEnum.Miku.getKey();
        }
        return StrategyHandler.getStrategy(key).globalList(columnDataPageVo);
//         IPage page = new Page();
//         page.setSize(size);
//         page.setCurrent(current);
//         QueryWrapper<WebContent> queryWrapper = new QueryWrapper<>();
//         queryWrapper.eq("website_id", websiteId);
//         queryWrapper.eq("status", 1);
//         queryWrapper.and(wrapper -> wrapper.like("original_content", content).or().like("content_title", content));
//         //queryWrapper.and(wrapper -> wrapper.like("content", content));
//         if (StringUtils.isNotBlank(beginDate)) {
//             queryWrapper.ge("publish_time", beginDate);
//         }
//         if (StringUtils.isNotBlank(endDate)) {
//             queryWrapper.le("publish_time", endDate);
//         }
//         if (id != null) {
//             queryWrapper.eq("id", id);
//         }
//         if (StringUtils.isNotBlank(createdBy)) {
//             queryWrapper.like("created_by", createdBy);
//         }
//         queryWrapper.orderByDesc("gmt_updated");
//         IPage result = contentMapper.selectPage(page, queryWrapper);
//         List<WebContent> records = result.getRecords();
//         LinkedList<WebContentVo> webContentVos = new LinkedList<>();
//         for (WebContent record : records) {
//             WebContentVo webContentVo = new WebContentVo();
//             BeanUtils.copyProperties(record, webContentVo);
//             Integer click = clickRateMapper.getClick(webContentVo.getId());
//             if (click == null) {
//                 click = NumberConstant.NUMBER_0;
//             }
//             webContentVo.setClickRate(click);
//             webContentVos.add(webContentVo);
//         }
//         result.setRecords(webContentVos);
//         return ResultVO.data(result);
    }

    @Override
    public ResultVO replaceContent(ReplaceContentVo replaceContentVo) {
        int key;
        if ("1".equals(WebsiteUtil.getWebsiteId())) {
            key = StrategyEnum.Aqua.getKey();
        } else {
            key = StrategyEnum.Miku.getKey();
        }
        return StrategyHandler.getStrategy(key).replaceContent(replaceContentVo);
        // String sourceTextIllegal = juedgeReplaceAble(replaceContentVo.getSourceText());
        // if (sourceTextIllegal != null) {
        //     return ResultVO.fail("包含不能被替换词" + sourceTextIllegal);
        // }
        // String targetTextIllegal = juedgeReplaceAble(replaceContentVo.getTargetText());
        // if (targetTextIllegal != null) {
        //     return ResultVO.fail("包含不能被替换词" + targetTextIllegal);
        // }
        // List<Integer> contentIds = replaceContentVo.getContentIds();
        // if (contentIds.size() < 1) {
        //     return ResultVO.fail(ResultCode.PARAM_INVALID);
        // }
        // contentMapper.repalceContent(replaceContentVo.getSourceText(), replaceContentVo.getTargetText(), replaceContentVo.getContentIds());
        // return ResultVO.success(ResultCode.SUCCESS);
    }

    private String juedgeReplaceAble(String text) {
        if (StringUtils.isNotBlank(text)) {
            boolean contains = MathcingConfig.completeMatchingSet.contains(text);
            if (contains) {
                return text;
            }
            for (String fuzzyWord : MathcingConfig.fuzzyMatchingSet) {
                if (text.contains(fuzzyWord)) {
                    return fuzzyWord;
                }
            }
        }
        return null;
    }


    @Override
    public ResultVO quoteList(Integer id, String createdBy, String beginDate, String endDate, String title, Integer status, Integer columnId, Integer current, Integer size) {
        return getquoteList(id, createdBy, beginDate, endDate, title, status, columnId, current, size);
    }

    @Override
    public ResultVO quoteListDashBoard(String beginDate, String endDate, String title, Integer status, Integer columnId, Integer current, Integer size) {
        if (columnId != null) {
            Column column = columnMapper.selectById(columnId);
            if (column != null && column.getColumnCount() != null) {
                size = column.getColumnCount();
            }
        }
        String redisStr = JedisPoolFactory.select(REDIS_PREFIX + QUOTE_LIST + columnId);
        if (redisStr != null) {
            return ResultVO.data(JSONObject.parseObject(redisStr));
        }
        return getquoteList(null, null, beginDate, endDate, title, status, columnId, current, size);
    }


    private ResultVO<?> getquoteList(Integer id, String createdBy, String beginDate, String endDate, String title, Integer status, Integer columnId, Integer current, Integer size) {
        if (current == null || current == 0) {
            current = 1;
        }
        current = current - 1;
        current = current * 10;
        String columnName = "";
        String enName = "";
        Column column = columnMapper.selectById(columnId);
        columnName = column.getColumnName();
        enName = column.getEnName();
        List<WebContentVo> webContentVos = contentMapper.quoteList(id, createdBy, beginDate, endDate, title, status, columnId, current, size);
        for (WebContentVo webContentVo : webContentVos) {
            Integer click = clickRateMapper.getClick(webContentVo.getId());
            if (click == null) {
                click = NumberConstant.NUMBER_0;
            }
            webContentVo.setClickRate(click);
            if (StringUtils.isNotBlank(webContentVo.getPicUrl())) {
                JSONArray jsonArray = JSONArray.parseArray(webContentVo.getPicUrl());
                webContentVo.setPicUrlJson(jsonArray);
            } else {
                webContentVo.setPicUrlJson(new JSONArray());
            }
        }
        Page pages = PageUtil.getPages(current, size, webContentVos);
        JedisPoolFactory.setex(REDIS_PREFIX + QUOTE_LIST + columnId, 30, JSONArray.toJSONString(pages, SerializerFeature.WriteDateUseDateFormat));
        return ResultVO.data(pages);
    }

    @Override
    public ResultVO saveQuote(QuoteVO quoteVO) {
        HashMap map = new HashMap();
        map.put("content_id", quoteVO.getContentId());
        quoteMapper.deleteByMap(map);
        List<Integer> columnIds = quoteVO.getColumnIds();
        for (Integer columnId : columnIds) {
            QueryWrapper<WebQuoteContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("column_id", columnId);
            queryWrapper.eq("content_id", quoteVO.getContentId());
            WebQuoteContent sqlQuote = quoteMapper.selectOne(queryWrapper);
            if (sqlQuote != null) {
                return ResultVO.fail("已引用该文章");
            }
            WebQuoteContent webQuoteContent = new WebQuoteContent();
            webQuoteContent.setContentId(quoteVO.getContentId());
            webQuoteContent.setColumnId(columnId);
            Date date = new Date();
            webQuoteContent.setGmtUpdated(date);
            webQuoteContent.setGmtCreated(date);
            webQuoteContent.setStatus(1);
            quoteMapper.insert(webQuoteContent);
        }
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO deleteQuote(WebQuoteContent webQuoteContent) {
        HashMap map = new HashMap();
        map.put("column_id", webQuoteContent.getColumnId());
        map.put("content_id", webQuoteContent.getContentId());
        quoteMapper.deleteByMap(map);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO query(Integer id) {
        countQuery(id);
        String redisStr = JedisPoolFactory.select(REDIS_PREFIX + CONTENTKEY + id);
        WebContentVo webContentVo = new WebContentVo();
        if (redisStr != null) {
            webContentVo = JSONObject.parseObject(redisStr, WebContentVo.class);
        } else {
            WebContent webContent = contentMapper.selectById(id);
            BeanUtils.copyProperties(webContent, webContentVo);
            if (StringUtils.isNotBlank(webContentVo.getPicUrl())) {
                JSONArray jsonArray = JSONArray.parseArray(webContentVo.getPicUrl());
                webContentVo.setPicUrlJson(jsonArray);
            } else {
                webContentVo.setPicUrlJson(new JSONArray());
            }
            //标签查询
            List<ContentRefMediatag> refList = contntRefMediatagMapper.selectList(new QueryWrapper<ContentRefMediatag>().eq("content_id", id));
            if (refList != null && refList.size() > 0) {
                List<Integer> tagIds = refList.stream().map(a -> a.getMediaTagId()).collect(Collectors.toList());
                List<MediaTag> mediaTags = mediaTagMapper.selectBatchIds(tagIds);
                List<Integer> groupIds = mediaTags.stream().map(a -> a.getTagGroupId()).distinct().collect(Collectors.toList());
                List<MediaTagGroup> mediaTagGroups = new ArrayList<>();
                if (groupIds.size() > 0) {
                    mediaTagGroups = mediaTagGroupMapper.selectBatchIds(groupIds);
                }
                ArrayList<TagGroupVo> tagGroupVos = new ArrayList<>();
                for (MediaTagGroup mediaTagGroup : mediaTagGroups) {
                    TagGroupVo tagGroupVo = new TagGroupVo();
                    tagGroupVo.setId(mediaTagGroup.getId());
                    tagGroupVo.setName(mediaTagGroup.getMediaGroupName());
                    ArrayList<ContentTagVo> contentTagVos = new ArrayList<>();
                    mediaTags.forEach(a -> {
                        if (a.getTagGroupId() == mediaTagGroup.getId()) {
                            ContentTagVo contentTagVo = new ContentTagVo();
                            contentTagVo.setId(a.getId());
                            contentTagVo.setName(a.getMediaTagName());
                            contentTagVos.add(contentTagVo);
                        }
                    });
                    tagGroupVo.setTagVoList(contentTagVos);
                    tagGroupVos.add(tagGroupVo);
                }
                webContentVo.setTagGroup(tagGroupVos);
            }
            JedisPoolFactory.setex(REDIS_PREFIX + CONTENTKEY + id, 3600, JSONObject.toJSONString(webContentVo));
        }

        return ResultVO.data(webContentVo);
    }


    /**
     * 记录访问量
     *
     * @param id
     */
    private void countQuery(Integer id) {
        String select = JedisPoolFactory.select(REDIS_PREFIX + CLICKRATE + id + StringPool.UNDERSCORE + NUMBER);
        if (select == null) {
            JedisPoolFactory.setex(REDIS_PREFIX + CLICKRATE + id + StringPool.UNDERSCORE + NUMBER, 86400, "1");
        } else {
            JedisPoolFactory.incr(REDIS_PREFIX + CLICKRATE + id + StringPool.UNDERSCORE + NUMBER);
        }
    }

    public ResultVO clickRateList(Integer[] ids) {
        if (ids.length < 1) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        List<Integer> integers = Arrays.asList(ids);
        List<ClickRateVo> clickList = clickRateMapper.getClickList(integers);
        List<Integer> collect = clickList.stream().map(a -> a.getContentId()).collect(Collectors.toList());
        for (int i = 0; i < ids.length; i++) {
            if (collect.contains(ids[i])) {
                continue;
            } else {
                ClickRateVo clickRateVo = new ClickRateVo();
                clickRateVo.setContentId(ids[i]);
                clickRateVo.setTotalCLick(0);
                clickList.add(clickRateVo);
            }
        }
        return ResultVO.data(clickList);
    }

    /**
     * 分词查询稿件
     *
     * @param content     搜索内容
     * @param current     当前页
     * @param size        每页显示数量
     * @param timeRange   时间范围 0所有 1一周内 2一月内3一年内
     * @param searchRange 搜索范围0所有1标题2正文
     * @return
     */
    @Override
    public ResultVO search(Integer websiteId, String content, Integer current, Integer size, Integer timeRange, Integer searchRange) {

        //1.直接按搜索内容查找
        IPage<WebContent> page = new Page(current, size);

        if (current < 0 || size <= 0 || StringUtils.isBlank(content)) {
            page.setRecords(Collections.emptyList());
            page.setTotal(0);
            return ResultVO.data(page);
        }
        try {
            page = contentMapper.selectPage(page, getWebContents(websiteId, content, timeRange, searchRange));
            if (page.getTotal() > 0) return ResultVO.data(page);

            //2.第一步查找失败变为分词查找
            Map<String, Object> params = new HashMap<>();
            params.put("text", content);
            ResultVO<?> resultVO = algorithmClient.chineseSegment(new JSONObject(params).toJSONString());
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(resultVO));
            List<String> participles = JSONObject.parseObject(jsonObject.getString("data"), new TypeReference<List<String>>() {
            });
            if (CollectionUtils.isEmpty(participles)) return ResultVO.data(page);

            CountDownLatch countDownLatch = new CountDownLatch(participles.size());
            List<FutureTask<List<WebContent>>> futureTasks = new ArrayList<>(participles.size());
            participles.forEach(p -> {
                FutureTask<List<WebContent>> futureTask = new FutureTask<>(new SearchTask(countDownLatch, current, size, p, websiteId, timeRange, searchRange));
                GlobalThreadPoolExecutor.poolExecutor.submit(futureTask);
                futureTasks.add(futureTask);
            });

            countDownLatch.await(10, TimeUnit.SECONDS);

            //多线程查找结果聚合
            Set<WebContent> webContents = new HashSet<>();

            for (FutureTask<List<WebContent>> futureTask : futureTasks) {
                webContents.addAll(futureTask.get());
            }

            Integer s = (current - 1) * size > webContents.size() ? webContents.size() : (current - 1) * size;
            Integer e = s + size > webContents.size() ? webContents.size() : s + size;
            List<WebContent> participleResult = webContents.stream().sorted(Comparator.comparing(WebContent::getId)).collect(Collectors.toList()).subList(s, e);
            page.setRecords(participleResult);
            page.setTotal(participleResult.size());
        } catch (Exception e) {
            log.error("稿件搜索失败{},原因:{}", content, e.getMessage());
            return ResultVO.data(ResultCode.FAILURE.getCode(), page, ResultCode.FAILURE.getMessage());
        }

        return ResultVO.data(page);
    }

    @Override
    public ResultVO queryQuoteListByContentId(Integer contentId) {
        QueryWrapper<WebQuoteContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id", contentId);
        List<WebQuoteContent> webQuoteContents = quoteMapper.selectList(queryWrapper);
        List<Integer> columnIds = webQuoteContents.stream().map(a -> a.getColumnId()).collect(Collectors.toList());
        return ResultVO.data(columnIds);
    }

    @Override
    public ResultVO queryMaxContentId() {
        int maxContentId;
        String lockResult = JedisPoolFactory.lock(LOCK_KEY, System.currentTimeMillis() + "", 5);
        if (LOCK_SUCCESS.equals(lockResult)) {
/*            QueryWrapper<SystemDictionary> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dictionary_key", "contentMaxId");
            SystemDictionary systemDictionary = systemDictionaryMapper.selectOne(queryWrapper);
            String dictionaryValue = systemDictionary.getDictionaryValue();
            maxContentId = Integer.parseInt(dictionaryValue);
            maxContentId = maxContentId + 1;
            systemDictionary.setDictionaryValue(maxContentId + "");
            systemDictionaryMapper.updateById(systemDictionary);*/
            maxContentId = contentMapper.queryMaxCount() + 1;
            JedisPoolFactory.delete(LOCK_KEY);
        } else {
            return ResultVO.fail("当前并发量过高,请稍后重试");
        }
        return ResultVO.data(maxContentId);
    }

    @Override
    public ResultVO stickQuote(WebQuoteContent webQuoteContent) {
        QueryWrapper<WebQuoteContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id", webQuoteContent.getContentId());
        queryWrapper.eq("column_id", webQuoteContent.getColumnId());
        WebQuoteContent dbWebQuoteContent = quoteMapper.selectOne(queryWrapper);
        dbWebQuoteContent.setGmtUpdated(new Date());
        quoteMapper.updateById(dbWebQuoteContent);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO stick(Integer id) {
        WebContent webContent = contentMapper.selectById(id);
        webContent.setTopTime(new Date());
        contentMapper.updateById(webContent);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO contentListByTagId(Integer size, Integer current, Integer mediaTagId, Integer moudleId, Integer centerId, Integer type) {
        Integer columnId = null;
        List<Integer> integers = columnMapper.selectByMoudleId(moudleId);
        if (integers.size() > 0) {
            if (type != null && type != 0) {
                columnId = integers.get(type);
            } else {
                columnId = integers.get(0);
            }
        }
        if (current == null || current == 0) {
            current = 1;
        }
        current = current - 1;
        if (size == null) {
            size = 9;
        }
        current = current * size;
        String redisKey = REDIS_PREFIX + CONTENT_LIST + "size_" + size + "current_" + current + "tagId_" + mediaTagId + "moudleId_" + moudleId + "centerId" + centerId + "type" + type;
        String redisStr = JedisPoolFactory.select(redisKey);
        if (redisStr != null) {
            return ResultVO.data(JSONObject.parseObject(redisStr));
        }
        List<WebContentPublishVo> webContentVos = contentMapper.contentListByTagId(mediaTagId, columnId, centerId, current, size);
        List<WebContentPublishVo> webContentPublishVos = contentMapper.contentTotalByTagId(mediaTagId, columnId, centerId);
        Integer total = webContentPublishVos.size();
        Integer pages = (total + size - 1) / size;
        webContentVos.forEach(a -> {
            if (a.getPicUrl() != null) {
                JSONArray jsonArray = JSONArray.parseArray(a.getPicUrl());
                a.setPicUrlJson(jsonArray);
            } else {
                a.setPicUrlJson(new JSONArray());
            }
            if (a.getPublishTime() != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    a.setPublishTime(sdf.format(sdf.parse(a.getPublishTime())));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
        HashMap result = new HashMap();
        result.put("records", webContentVos);
        result.put("total", total);
        result.put("pages", pages);
        JedisPoolFactory.setex(redisKey, 30, JSONArray.toJSONString(result, SerializerFeature.WriteDateUseDateFormat));
        return ResultVO.data(result);
    }

    @Override
    public ResultVO queryTagByColumnId(String columnId, String centerId) {
        return ResultVO.data(contentMapper.queryTagByColumnId(columnId, centerId));
    }

    @Override
    public ResultVO queryTagByMoudleId(String moudleId, String centerId) {
        List<Integer> integers = columnMapper.selectByMoudleId(Integer.parseInt(moudleId));
        if (integers.size() > 0) {
            return queryTagByColumnId(integers.get(0).toString(), centerId);
        }
        return ResultVO.data(ResultCode.FAILURE);
    }

    @Override
    public ResultVO queryPicUrlById(String columnId, String type) {
        Column column = columnMapper.selectById(columnId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("columnName", column.getColumnName());
        jsonObject.put("enName", column.getEnName());
        jsonObject.put("records", contentMapper.queryPicUrlById(columnId, type));
        return ResultVO.data(jsonObject);
    }

    @Override
    public void importExcel(MultipartFile file) {
        try {
            int successCount = 0;
            int errorCount = 0;
            WebContent webContent;
            WebContentDto webContentDto;
            //1. 读取一个文件,将文件转换成工作簿(WorkBook)
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            //2. 从工作簿中读取工作表
            Sheet sheet = workbook.getSheetAt(0);//根据索引获取工作表
            //3. 从工作表中读取行(在获取最后一行的时候,+1操作)
            for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
                webContent = new WebContent();
                webContentDto = new WebContentDto();
                Row row = sheet.getRow(i);
                //4. 从行中读取单元格
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j);
                    //5. 从单元格中读取值
                    if (cell != null) {
                        String cellValue = ExcelUtil.getCellValue(cell) + "";
                        if (!cellValue.equals("null")) {
                            Field[] fields = webContentDto.getClass().getDeclaredFields();
                            fields[j].setAccessible(true);
                            fields[j].set(webContentDto, cellValue);
                        }
                    }
                }
                BeanUtils.copyProperties(webContentDto, webContent);
                if (StringUtils.isNotBlank(webContentDto.getColumnId())) {
                    webContent.setColumnId(Double.valueOf(webContentDto.getColumnId()).intValue());
                }
                String inputtime = webContentDto.getInputtime();
                if (StringUtils.isNotBlank(inputtime)) {
                    Date dt = new Date(Long.parseLong(inputtime) * 1000);
//                    SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//                    String format = sfd.format(dt);
                    webContent.setPublishTime(dt);
                }
                //5.插入数据库
                webContent.setStatus(NumberConstant.NUMBER_1);
                webContent.setIsDeleted(NumberConstant.NUMBER_0);
                webContent.setGmtCreated(new Date());
                webContent.setGmtUpdated(new Date());
                //webContent.setPublishTime(new Date());
                if (StringUtils.isNotBlank(webContent.getContent())) {
                    webContent.setContent(webContent.getContent());
                }
                if (StringUtils.isNotBlank(webContent.getContentTitle())) {
                    webContent.setContentTitle(webContent.getContentTitle());
                }
                Integer columnId = webContent.getColumnId();
                if (columnId != null) {
                    if (columnId == 53) {
                        webContent.setColumnId(41);
                    } else if (columnId == 148) {
                        webContent.setColumnId(1);
                    } else if (columnId == 56) {
                        webContent.setColumnId(53);
                    } else if (columnId == 54) {
                        webContent.setColumnId(42);
                    } else if (columnId == 58) {
                        webContent.setColumnId(43);
                    } else if (columnId == 61) {
                        webContent.setColumnId(56);
                    } else if (columnId == 66) {
                        webContent.setColumnId(48);
                    } else if (columnId == 82) {
                        webContent.setColumnId(35);
                    } else if (columnId == 84
                            || columnId == 87
                            || columnId == 90
                            || columnId == 93
                            || columnId == 96
                            || columnId == 105
                            || columnId == 1
                            || columnId == 146) {
                        webContent.setColumnId(40);
                    } else if (columnId == 80) {
                        webContent.setColumnId(16);
                    } else if (columnId == 79) {
                        webContent.setColumnId(17);
                    } else if (columnId == 320) {
                        webContent.setColumnId(45);
                    } else if (columnId == 314) {
                        webContent.setColumnId(46);
                    } else if (columnId == 143) {
                        webContent.setColumnId(36);
                    } else if (columnId == 319) {
                        webContent.setColumnId(44);
                    } else {
                        continue;
                    }
                }
                try {
                    if (StringUtils.isNotEmpty(webContent.getPicUrl())) {
                        UploadVo uploadVo = fileClient.uploadByUrl(webContent.getPicUrl(), "1");
                        JSONArray jsonArray = new JSONArray();
                        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(uploadVo.getData()));
                        JSONObject json = new JSONObject();
                        json.put("mediaId", jsonObject.get("id"));
                        json.put("url", jsonObject.get("url"));
                        json.put("name", jsonObject.get("name"));
                        json.put("type", NumberConstant.NUMBER_0);
                        jsonArray.add(json);
                        webContent.setPicUrl(jsonArray.toJSONString());
                    }
                    if (webContent.getColumnId() != null) {
                        Column column = columnMapper.selectById(webContent.getColumnId());
                        Moudle moudle = moudleMapper.selectById(column.getMoudleId());
                        webContent.setPath(moudle.getMoudleName() + "/" + column.getColumnName());
                    }
                    webContent.setCreatedBy("superadmin");
                    if (webContent.getContent() != null && webContent.getOriginalContent() == null) {
                        String clean = Jsoup.clean(webContent.getContent(), Whitelist.none());
                        webContent.setOriginalContent(clean);
                    }
                    String websiteId = WebsiteUtil.getWebsiteId();
                    if (StringUtils.isBlank(websiteId)) {
                        continue;
                    } else {
                        webContent.setWebsiteId(Integer.parseInt(websiteId));
                    }
                    if (StringUtils.isBlank(webContent.getPicUrl())) {
                        continue;
                    }
                    contentMapper.insert(webContent);
                    insertFileRefContent(webContent);
                    if (webContent.getColumnId() != null) {
                        WebQuoteContent webQuoteContent = new WebQuoteContent();
                        webQuoteContent.setContentId(webContent.getId());
                        webQuoteContent.setGmtCreated(new Date());
                        webQuoteContent.setGmtUpdated(new Date());
                        if (webContent.getColumnId() == 41) {
                            webQuoteContent.setColumnId(3);
                        } else if (webContent.getColumnId() == 1) {
                            webQuoteContent.setColumnId(1);
                        } else if (webContent.getColumnId() == 42) {
                            webQuoteContent.setColumnId(2);
                        } else if (webContent.getColumnId() == 48) {
                            webQuoteContent.setColumnId(4);
                        } else if (webContent.getColumnId() == 35 ||
                                webContent.getColumnId() == 36 ||
                                webContent.getColumnId() == 40) {
                            webQuoteContent.setColumnId(5);
                        } else if (webContent.getColumnId() == 53) {
                            webQuoteContent.setColumnId(6);
                        }
                        if (webQuoteContent.getColumnId() != null && (
                                webQuoteContent.getColumnId() == 1 ||
                                        webQuoteContent.getColumnId() == 2 ||
                                        webQuoteContent.getColumnId() == 3 ||
                                        webQuoteContent.getColumnId() == 4 ||
                                        webQuoteContent.getColumnId() == 5 ||
                                        webQuoteContent.getColumnId() == 6)) {
                            quoteMapper.insert(webQuoteContent);
                        }
                    }
                    successCount++;
                    log.info("导入了{}", webContent);
                } catch (Exception e) {
                    errorCount++;
                    log.info("导入失败{}", webContent);
                    e.printStackTrace();
                }
            }
            System.out.println("--------------------------------------");
            System.out.println("--------------------------------------");
            System.out.println("--------------------------------------");
            System.out.println("导入完成,成功:" + successCount + "条,失败:" + errorCount + "条");
            System.out.println("--------------------------------------");
            System.out.println("--------------------------------------");
            System.out.println("--------------------------------------");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void insertFileRefContent(WebContent webContent) {
        if (webContent.getPicUrl() != null && webContent.getId() != null) {
            QueryWrapper<FileRefContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("content_id", webContent.getId());
            fileRefContentMapper.delete(queryWrapper);
            JSONArray jsonArray = JSONArray.parseArray(webContent.getPicUrl());
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                if (jsonObject.get("mediaId") == null) {
                    continue;
                }
                String mediaId = jsonObject.get("mediaId").toString();
                FileRefContent fileRefContent = new FileRefContent();
                fileRefContent.setContentId(webContent.getId());
                fileRefContent.setFileId(Long.parseLong(mediaId));
                fileRefContent.setGmtCreated(new Date());
                fileRefContent.setGmtUpdated(new Date());
                fileRefContentMapper.insert(fileRefContent);
                if (webContent.getColumnId() == 53) {
                    SystemFileRefSubject systemFileRefSubject = new SystemFileRefSubject();
                    SystemFileRefTag systemFileRefTag = new SystemFileRefTag();
                    systemFileRefSubject.setFileId(Long.parseLong(mediaId));
                    systemFileRefSubject.setMediaTagId(1);
                    systemFileRefSubject.setGmtCreated(new Date());
                    systemFileRefSubject.setGmtUpdated(new Date());
                    systemFileRefTag.setFileId(Long.parseLong(mediaId));
                    systemFileRefTag.setMediaTagId(61);
                    systemFileRefTag.setGmtCreated(new Date());
                    systemFileRefTag.setGmtUpdated(new Date());
                    systemFileRefSubjectMapper.insert(systemFileRefSubject);
                    systemFileRefTagMapper.insert(systemFileRefTag);

                }
            }
        }
    }

    @Override
    public void addSummary() {
        QueryWrapper<WebContent> queryWrapper = new QueryWrapper<>();
        List<WebContent> webContents = contentMapper.selectList(queryWrapper);
        for (WebContent webContent : webContents) {
            try {
                String originalContent = webContent.getOriginalContent();
                if (StringUtils.isNotBlank(originalContent)) {
                    String[] split = originalContent.split("。");
                    if (split.length > 0 && !split[0].equals("")) {
                        if (split[0].length() > 300) {
                            webContent.setContentAbstract(split[0].substring(0, 300));
                        } else if (split[0].length() < 30 && originalContent.length() >= 30) {
                            webContent.setContentAbstract(originalContent.substring(0, 30));
                        } else {
                            webContent.setContentAbstract(split[0]);
                        }
                    } else {
                        webContent.setContentAbstract(originalContent.substring(0, 15));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                contentMapper.updateById(webContent);
            }
        }
        System.out.println("执行完毕");
    }

    @Override
    public void deleteNull() {
        List<WebContent> webContents = contentMapper.selectList(null);
        for (WebContent webContent : webContents) {
            String originalContent = webContent.getOriginalContent();
            if (StringUtils.isBlank(originalContent)) {

                contentMapper.deleteById(webContent.getId());
                System.out.println("删除了id为" + webContent.getId() + "的内容");
            } else {
                //originalContent = originalContent.replaceAll("你的浏览器不支持H5视频播放，请升级浏览器", "");
                originalContent = originalContent.replaceAll("&nbsp;", "");
                webContent.setOriginalContent(originalContent);
                webContent.setGmtUpdated(webContent.getPublishTime());
                //webContent.setContentAbstract(webContent.getContentAbstract().replaceAll("你的浏览器不支持H5视频播放，请升级浏览器", ""));
                webContent.setContentAbstract(webContent.getContentAbstract().replaceAll("&nbsp;", ""));
                contentMapper.updateById(webContent);
                System.out.println("更新了id为" + webContent.getId() + "的内容");
            }
        }
        System.out.println("执行完毕");
    }

    @Override
    public void deleteDulList() {
        List<WebContent> webContents = contentMapper.selectList(null);
        for (WebContent webContent : webContents) {
            QueryWrapper<WebContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("content_title", webContent.getContentTitle());
            List<WebContent> webContents1 = contentMapper.selectList(queryWrapper);
            if (webContents1.size() == 2) {
                for (int i = 0; i < webContents1.size(); i++) {
                    if (webContents1.get(0).getOriginalContent().length() > webContents1.get(1).getOriginalContent().length()) {
                        contentMapper.deleteById(webContents1.get(1).getId());
                    } else {
                        contentMapper.deleteById(webContents1.get(0).getId());
                    }
                }
            }
        }
        System.out.println("执行完毕");
    }

    @Override
    public void timeList() {
        List<WebContent> webContents = contentMapper.selectList(null);
        for (WebContent webContent : webContents) {
            webContent.setGmtUpdated(webContent.getPublishTime());
            contentMapper.updateById(webContent);
        }
        System.out.println("执行完毕");
    }

    @Override
    public ResultVO<?> quoteListDashBoardPlus(String beginDate, String endDate, String title, Integer status, Integer columnId, Integer current, Integer size) {
        String redisStr = JedisPoolFactory.select(REDIS_PREFIX + HOME + columnId);
        if (redisStr != null) {
            return ResultVO.data(JSONObject.parseObject(redisStr));
        }
        return getquoteListPlus(null, null, beginDate, endDate, title, status, columnId, current, size);
    }

    private ResultVO<?> getquoteListPlus(Integer id, String createdBy, String beginDate, String endDate, String title, Integer status, Integer columnId, Integer current, Integer size) {
        if (current == null || current == 0) {
            current = 1;
        }
        current = current - 1;
        current = current * 10;
        String columnName = "";
        String enName = "";
        Column column = columnMapper.selectById(columnId);
        columnName = column.getColumnName();
        enName = column.getEnName();
        List<WebContentVo> webContentVos = contentMapper.quoteList(id, createdBy, beginDate, endDate, title, status, columnId, current, size);
        for (WebContentVo webContentVo : webContentVos) {
            Integer click = clickRateMapper.getClick(webContentVo.getId());
            if (click == null) {
                click = NumberConstant.NUMBER_0;
            }
            webContentVo.setClickRate(click);
            if (StringUtils.isNotBlank(webContentVo.getPicUrl())) {
                JSONArray jsonArray = JSONArray.parseArray(webContentVo.getPicUrl());
                webContentVo.setPicUrlJson(jsonArray);
            } else {
                webContentVo.setPicUrlJson(new JSONArray());
            }
        }
        Integer count = contentMapper.quoteListCount(id, createdBy, beginDate, endDate, title, status, columnId, current, size);
        HashMap result = new HashMap();
        result.put("records", webContentVos);
        result.put("total", count);
        result.put("columnName", columnName);
        result.put("enName", enName);
        JedisPoolFactory.setex(REDIS_PREFIX + HOME + columnId, 30, JSONArray.toJSONString(result, SerializerFeature.WriteDateUseDateFormat));
        return ResultVO.data(result);
    }

    @Override
    public ResultVO queryByMoudleId(Integer moudleId, Integer current, Integer size) {
        QueryWrapper<Column> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("moudle_id", moudleId);
        queryWrapper.ne("column_type", NumberConstant.NUMBER_0);
        queryWrapper.ne("column_type", NumberConstant.NUMBER_1);
        List<Column> columns = columnMapper.selectList(queryWrapper);
        JSONArray jsonArray = new JSONArray();
        for (Column column : columns) {
            if (column != null && column.getColumnCount() != null) {
                size = column.getColumnCount();
            }
            jsonArray.add(getContent(null, null, null, null, null, null, column.getId(), null, null, current, size));
        }
        return ResultVO.data(jsonArray);
    }

    class SearchTask implements Callable<List<WebContent>> {

        private CountDownLatch countDownLatch;
        private long current;
        private long size;
        private String content;
        private Integer websiteId;
        private Integer timeRange;
        private Integer searchRange;

        public SearchTask(CountDownLatch countDownLatch, long current, long size, String content, Integer websiteId, Integer timeRange, Integer searchRange) {
            this.current = current;
            this.size = size;
            this.countDownLatch = countDownLatch;
            this.content = content;
            this.websiteId = websiteId;
            this.timeRange = timeRange;
            this.searchRange = searchRange;
        }

        @Override
        public List<WebContent> call() {
            try {
                return contentMapper.selectList(getWebContents(websiteId, content, timeRange, searchRange));
            } catch (Exception e) {
                log.error("稿件分词搜索失败{}", content);
            } finally {
                countDownLatch.countDown();
            }
            return Collections.emptyList();
        }
    }

    private static QueryWrapper<WebContent> getWebContents(Integer websiteId, String content, Integer timeRange, Integer searchRange) {
        if (Objects.isNull(websiteId)) websiteId = 1;
        QueryWrapper<WebContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("website_id", websiteId);
        queryWrapper.eq("status", NumberConstant.NUMBER_1);
        queryWrapper.notLike("path", "之江景");
        queryWrapper.orderByDesc("publish_time");

        if (StringUtils.isNotBlank(content)) getSearchRange(queryWrapper, searchRange, content);

        getTimeRange(queryWrapper, timeRange);


        return queryWrapper;
    }

    private static void getSearchRange(QueryWrapper<WebContent> queryWrapper, Integer searchRange, String content) {
        switch (searchRange) {
            case 1:
                queryWrapper.like("content_title", content);
                break;
            case 2:
                queryWrapper.like("original_content", content);
                break;
            default:
                queryWrapper.and(qw -> qw.like("content_title", content).or().like("content_abstract", content).or().like("original_content", content));
                break;
        }
    }

    private static void getTimeRange(QueryWrapper queryWrapper, Integer timeRange) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDate = new Date();
        String sDate = format.format(currentDate);
        Calendar c = Calendar.getInstance();
        c.setTime(currentDate);

        switch (timeRange) {
            case 1://一周内
                c.add(Calendar.DATE, -7);
                break;
            case 2://一月内
                c.add(Calendar.MONTH, -1);
                break;
            case 3://一年内
                c.add(Calendar.YEAR, -1);
                break;
            default:
                return;
        }

        String eDate = format.format(c.getTime());

        queryWrapper.le("publish_time", sDate);
        queryWrapper.ge("publish_time", eDate);
    }

    @Override
    public ResultVO updateStatus(Integer id) {
        WebContent webContent = contentMapper.selectById(id);
        if (webContent != null) {
            webContent.setStatus(1);
            webContent.setPublishTime(new Date());
            contentMapper.updateById(webContent);
        }
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO init() {
        List<WebContent> webContents = contentMapper.selectList(new LambdaQueryWrapper<WebContent>().eq(WebContent::getStatus, 1).and(x -> x.eq(WebContent::getColumnId, 40).or().eq(WebContent::getColumnId, 72)));
        for (WebContent webContent : webContents) {
            List<WebQuoteContent> webQuoteContents = quoteMapper.selectList(new LambdaQueryWrapper<WebQuoteContent>().eq(WebQuoteContent::getContentId, webContent.getId())
                    .eq(WebQuoteContent::getColumnId, webContent.getColumnId()));
            if (webQuoteContents.size() == 0) {
                WebQuoteContent webQuoteContent = new WebQuoteContent();
                webQuoteContent.setContentId(webContent.getId());
                webQuoteContent.setColumnId(webContent.getColumnId());
                webQuoteContent.setStatus(1);
                webQuoteContent.setGmtCreated(new Date());
                webQuoteContent.setGmtUpdated(new Date());
                quoteMapper.insert(webQuoteContent);
                log.info("插入了，{}", webQuoteContent);
            }
        }
        return ResultVO.success(ResultCode.SUCCESS);
    }
}
